#!/usr/bin/env bash

source ../../lib/shell/env.sh
source ../../lib/shell/common.sh

function calculate_pi() {
    local cmd="echo \"scale=5000; 4*a(1)\" | bc -l"

    echo -e "${cmd}" >> $CPU_PI_TEST_LOG
    if eval $cmd >> $CPU_PI_TEST_LOG;then
        cmd="${cmd}| md5sum | grep -wq \"5710ed0cb5dfda82f3ba3551f8126378\""
        if eval $cmd;then
            echo -e "Successfully execute: [eval $cmd]" >> $CPU_PI_TEST_LOG
        else
            echo -e "Failed to exec: [eval $cmd]" >> $CPU_PI_TEST_LOG
        fi
    else
        echo -e "Failed to exec: [eval $cmd]" >> $CPU_PI_TEST_LOG
    fi
}

function monitor_cpu_load() {
    local load_msg=""
    local cur_ldavg=60
    CUR_CPU_LOAD=$(sar -q 1 15|awk '/Average/{print $4}')

    if [ $(echo "scale=2; $CUR_CPU_LOAD > $START_CPU_LOAD" |bc) -eq 1 ];then
        load_msg="${load_msg}CPULOAD: ${START_CPU_LOAD}(start load) ${CUR_CPU_LOAD}(current load) ldavg($cur_ldavg),it's Successfully!\n"
    else
        echo "============[cpuload exception]=================="
        sar -q 1 1 >> $CPU_PI_TEST_LOG
        load_msg="${load_msg}CPULOAD: ${START_CPU_LOAD}(start load) ${CUR_CPU_LOAD}(current load) ldavg($cur_ldavg), it's Failed.\n"
        echo -e "${load_msg}"
    fi
    echo -e "${load_msg}" >> $CPU_PI_TEST_LOG
}

function run_test() {
    local cur_time=0
    local cur_time_diff=0
    local ldavg="[ldavg-1]"

    [ ! -d "$(dirname $CPU_PI_TEST_LOG)" ] && mkdir -p $(dirname $CPU_PI_TEST_LOG)

    echo "Get cpuload [runtime ${RUNTIME}s]."
    START_CPU_LOAD=$(sar -q 1 10|awk '/Average/{print $4}')
    echo "==========[CPULOAD: $START_CPU_LOAD]=========="
    for ((i=1;i<=$RUNTIME;i+=$cur_time_diff));do
        echo -e "\n=========================="
        echo "CPU pi test in ${i}s--->[runtime: ${RUNTIME}s]"

        [ -f $CPU_PI_TEST_LOG ] && rm -rf $CPU_PI_TEST_LOG
        echo "${ldavg} latest cpu load info" >>$CPU_PI_TEST_LOG
        sar -q 1 1 >>$CPU_PI_TEST_LOG
        cur_time="$(date +%s -d "$(date +"%a %b %e %T %Y")")"

        for ((n=1;n<=3;n++));do
            calculate_pi &
        done
        echo "Monitor cpuload......"
        sleep 5
        monitor_cpu_load &
        wait

        cur_time_diff=$(($(date +%s -d "$(date +"%a %b %e %T %Y")") - $cur_time))
        if [ $(($i + 2 * $cur_time_diff)) -ge $RUNTIME ];then
            echo "Cpu pi test is completed, check the result ..."
            if cat $CPU_PI_TEST_LOG|grep -iwq "Failed";then
                cat $CPU_PI_TEST_LOG |grep -iw "Failed" && return 1
            else
                echo -e "\n===========[CPU pi test results]==============="
                echo "cpu pi test log--->$CPU_PI_TEST_LOG"
                while read line;do echo $line;done < $CPU_PI_TEST_LOG
                return 0
            fi
        fi
    done
}

stress_cpu_env
trap "[ -f $CPU_PI_TEST_LOG ] && rm -rf $CPU_PI_TEST_LOG" EXIT

# # # # # # # # # # # # # # main # # # # # # # # # # # #
run_test && test_pass || test_fail
